//
//  TryHoneCacheManager.m
//  TryHoneBase
//
//  Created by TryHone on 17/6/16.
//  Copyright © 2017年 TryHone. All rights reserved.
//

#import "JFCacheManager.h"
#import "JFStringHelper.h"
#import "JFLogHelper.h"
#import "JFFileHelper.h"
#import "JFMacro.h"
#define TRYHONE_CACHE_ENGINENAME @"TRYHONE_CACHE_ENGINENAME_DEFAULT"

#if __has_include(<YYCache/YYCache.h>)
#import <YYCache/YYCache.h>
#else
#import "YYCache.h"
#endif


@interface JFCacheManager()
@property(nonatomic,strong) NSMutableDictionary*engineYYCacheMap;
@property(nonatomic,strong) NSMutableDictionary*engineNSUserDefaultMap;
@end
@implementation JFCacheManager

+ (instancetype)sharedInstance {
    static JFCacheManager *_sharedClient = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedClient = [[JFCacheManager alloc] init];
    });
    return _sharedClient;
}

+(NSString*)defaultEngineName{
    return TRYHONE_CACHE_ENGINENAME;
}

-(instancetype)init{
    self = [super init];
    if (self) {
        _engineYYCacheMap = [[NSMutableDictionary alloc] init];
        _engineNSUserDefaultMap = [[NSMutableDictionary alloc] init];
    }
   return self;
}
-(NSMutableDictionary*)engineYYCacheMap{
    if (!_engineYYCacheMap) {
        _engineYYCacheMap = [[NSMutableDictionary alloc] init];
    }
    return _engineYYCacheMap;
}

-(NSMutableDictionary*)engineNSUserDefaultMap{

    if (!_engineNSUserDefaultMap) {
        _engineNSUserDefaultMap = [[NSMutableDictionary alloc] init];
    }
    return _engineNSUserDefaultMap;
}
-(void)setYYCacheEngine:(id)engine key:(NSString*)engineName{
    if ([JFStringHelper isNotEmpty:engineName]) {
       self.engineYYCacheMap[engineName] = engine;
    }
}
-(void)setNSUserDefaultEngine:(id)engine key:(NSString*)engineName{
    if ([JFStringHelper isNotEmpty:engineName]) {
        self.engineNSUserDefaultMap[engineName] = engine;
    }
}


-(id)enginYYCacheByName:(NSString*)name{
    if ([JFStringHelper isNotEmpty:name]) {
        YYCache * YYCacheInstance = self.engineYYCacheMap[name];
        if (!YYCacheInstance) {
            YYCacheInstance = [[YYCache alloc] initWithPath:[self getYYCachePath:name]];
            [[JFCacheManager sharedInstance] setYYCacheEngine:YYCacheInstance key:name];
        }
        return YYCacheInstance;
    }
    
    return nil;
}
//把YYCache缓存目录放到Doc目录下面去
-(NSString*)getYYCachePath:(NSString*)name{
    NSString *docPath = [JFFileHelper documentFolder];
    NSString *path = [docPath stringByAppendingPathComponent:@"YYCacel"];
    path = [path stringByAppendingPathComponent:name];
    return path;
}
-(id)enginNSUserDefaultByName:(NSString*)name{
    if ([JFStringHelper isNotEmpty:name]) {
        NSUserDefaults * userDefaultsInstance = self.engineNSUserDefaultMap[name];
        if (!userDefaultsInstance) {
            userDefaultsInstance = [[NSUserDefaults alloc] initWithSuiteName:name];
            [[JFCacheManager sharedInstance] setNSUserDefaultEngine:userDefaultsInstance key:name];
        }
        return userDefaultsInstance;
    }
    return nil;
}

+(void)createEngine:(NSString*)engineName type:(CacheEngine)type{
   
    if ([JFStringHelper isNotEmpty:engineName]) {//不能创建为空的引擎
        if (type == CacheEngine_NSUserDefault) {
            [[JFCacheManager sharedInstance] enginNSUserDefaultByName:engineName];
        }else if (type == CacheEngine_YYCache){
            [[JFCacheManager sharedInstance] enginYYCacheByName:engineName];
        }
        
    }
}

/**
 *  @author Alan, 17-06-16 17:06:58
 *
 *  @brief 把数据存储到缓存
 *
 *  @param model 缓存模型
 */
+(void)sendDataToCacheWithModel:(JFCachelModel*)model{

    
    if ([JFCacheManager checkData:model]) {
        
        switch (model.engine) {
            case CacheEngine_YYCache:{
                YYCache * YYCacheInstance = [[JFCacheManager sharedInstance] enginYYCacheByName:model.engineName];
                if (YYCacheInstance) {
                   [YYCacheInstance setObject:model.cachelData forKey:model.key];
                }
            }break;
            case CacheEngine_NSUserDefault:{
                NSUserDefaults * userDefaultsInstance = [[JFCacheManager sharedInstance] enginNSUserDefaultByName:model.engineName];
                if (userDefaultsInstance) {
                    id  data = [NSKeyedArchiver archivedDataWithRootObject:model.cachelData];
                    [userDefaultsInstance setObject:data forKey:model.key];
                }
            }break;
            default:
                [JFLogHelper stringWriteLogToConsole:@"没有获取到引擎类型无法完成操作"];
                break;
        }
    }



}

+(BOOL)checkData:(JFCachelModel*)model{

    
    if (!model) {
        [JFLogHelper stringWriteLogToConsole:@"不能写入空数据到缓存"];
        return  false;
    }
    
    if(![model isKindOfClass:[JFCachelModel class]]){
        [JFLogHelper stringWriteLogToConsole:@"数据类型不正确"];
        return  false;
    }
    if (model.engine == CacheEngine_NONE) {
        [JFLogHelper stringWriteLogToConsole:@"引擎不正确，无法缓存数据"];
        return  false;
    }
    
    
    if (!(model.key && [model.key isKindOfClass:[NSString class]] && model.key.length)) {
        
        [JFLogHelper stringWriteLogToConsole:[NSString stringWithFormat:@"缓存key为空，无法缓存，model=%@",[model description]]];
        return  false;
    }
    
    if (!model.cachelData) {
        [JFLogHelper stringWriteLogToConsole:[NSString stringWithFormat:@"缓存值不能为nil，model=%@",[model description]]];
        return  false;
    }
    
    return  YES;
}


/**
 *  @author Alan, 17-06-16 17:06:58
 *
 *  @brief 要存储的数据
 *
 *  @param
 */
+(void)sendDataToCache:(id)data key:(NSString*)key{

    if (data ) {
        JFCachelModel * tempdata = data;
        if (![data isKindOfClass:[JFCachelModel class]]) {
            
            if (key && [key isKindOfClass:[NSString  class]] && key.length ) {
                tempdata = [JFCachelModel getInstance];
                tempdata.engine = CacheEngine_YYCache;
                tempdata.engineName = [JFCacheManager defaultEngineName];
                tempdata.cachelData = data;
                tempdata.key = key;
            }else{
                tempdata = nil;
            }

        }
        [JFCacheManager sendDataToCacheWithModel:tempdata];
        
    }else{
        [JFLogHelper stringWriteLogToConsole:@"数据非法"];
    }
}
/**
 *  @author Alan, 17-06-16 17:06:22
 *
 *  @brief 从默认缓存引擎中获取数据(先从YYCache中取，取不到会从NSUserDefaults中取)
 *
 *  @param key <#key description#>
 *
 *  @return <#return value description#>
 */
+(JFCachelModel*)vauleDataFromCacheWithKey:(NSString*)key{
  return  [self vauleDataFromCache:[JFCacheManager defaultEngineName] key:key];
}


/**
 *  @author Alan, 17-06-16 17:06:26
 *
 *  @brief  从engineName缓存引擎中获取数据(先从YYCache中取，取不到会从NSUserDefaults中取)
 *
 *  @param engineName 获取数据的缓存引擎
 *  @param key        key
 *
 *  @return <#return value description#>
 */
+(JFCachelModel*)vauleDataFromCache:(NSString*)engineName key:(NSString*)key{
    JFCachelModel * data = [JFCachelModel getInstance];
    data.engine = CacheEngine_NONE;
    data.engineName = engineName;
    data.key = key;
    id vauledata = [self vauleDataFromYYCache:engineName key:key];
    if (!vauledata) {
        vauledata = [self vauleDataFromNSUserdefault:engineName key:key];
        if (vauledata) {
            data.cachelData = vauledata;
            data.engine = CacheEngine_NSUserDefault;
        }
        return data;
    }
    data.cachelData = vauledata;
    data.engine = CacheEngine_YYCache;
    return data;
}
+(id)vauleDataFromYYCache:(NSString*)engineName key:(NSString*)key{
    YYCache * YYCacheInstance = [[JFCacheManager sharedInstance] enginYYCacheByName:engineName];
    if (YYCacheInstance) {
       return  [YYCacheInstance objectForKey:key];
    }else{
       return nil;
    }
    
}

+(id)vauleDataFromNSUserdefault:(NSString*)engineName key:(NSString*)key{
     NSUserDefaults * userDefaultsInstance = [[JFCacheManager sharedInstance] enginNSUserDefaultByName:engineName];
    if (userDefaultsInstance) {
        id data = [userDefaultsInstance objectForKey:key];
        return [NSKeyedUnarchiver unarchiveObjectWithData:data];
    }else{
        return nil;
    }

}


/**
 *  @author Alan, 17-06-17 14:06:18
 *
 *  @brief 移除默认引擎名key缓存存值(会移除YYCache,NSUserDefaults中key的值 )
 *
 *  @param key <#key description#>
 */
+(void)removeObjectForKey:(NSString*)key{
    [JFCacheManager removeObjectFrom:[JFCacheManager defaultEngineName] key:key];
}

/**
 *  @author Alan, 17-06-17 14:06:18
 *
 *  @brief 从指定引擎名移除指定key值
 *
 *  @param key key
 */
+(void)removeObjectFrom:(NSString*)engine key:(NSString*)key{

    if ([JFStringHelper isNotEmpty:engine]) {
        YYCache * yycacheInstance = [[JFCacheManager sharedInstance] enginYYCacheByName:engine];
        if (yycacheInstance) {
            [yycacheInstance removeObjectForKey:key];
        }
        NSUserDefaults *userDefaultInstance = [[JFCacheManager sharedInstance] enginNSUserDefaultByName:engine];
        if (userDefaultInstance) {
            [userDefaultInstance removeObjectForKey:key];
        }
    }


}
/**
 *  @author Alan, 17-06-17 14:06:07
 *
 *  @brief 从YYCache,NSUserDefaults 默认引擎名移除所有的缓存值
 */
+(void)removeAllObjectFromDefaultEngin{
    [JFCacheManager removeAllObjectFrom:[JFCacheManager defaultEngineName]];
}

/**
 *  @author Alan, 17-06-17 14:06:07
 *
 *  @brief 从YYCache,NSUserDefaults 默认引擎名移除所有的缓存值
 */
+(void)removeAllObjectFrom:(NSString*)engine{
    if ([JFStringHelper isNotEmpty:engine]) {
        YYCache * yycacheInstance = [[JFCacheManager sharedInstance] enginYYCacheByName:engine];
        if (yycacheInstance) {
            [yycacheInstance removeAllObjects];
        }
        NSUserDefaults *userDefaultInstance = [[JFCacheManager sharedInstance] enginNSUserDefaultByName:engine];
        if (userDefaultInstance) {
            NSDictionary* dict = [userDefaultInstance dictionaryRepresentation];
            for (id key in dict) {
                [userDefaultInstance removeObjectForKey:key];
            }
        }
    }
}




@end
